package org.zhou.demo1;

import java.util.List;

public class Adapter implements LogDbOperateApi {
    private LogFileOperateApi adaptee;

    public Adapter(LogFileOperateApi adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void createLog(LogModel logModel) {
        // 1.先读取文件的内容
        List<LogModel> logModels = this.adaptee.readLogFile();

        // 2.加入新的日志对象
        logModels.add(logModel);

        // 3.重新写入文件
        this.adaptee.writeLogFile(logModels);
    }

    @Override
    public void updateLog(LogModel logModel) {
        // 1.读取日志对象
        List<LogModel> logModels = this.adaptee.readLogFile();

        // 2.更新日志对象
        for (int i = 0; i < logModels.size(); i++) {
            if(logModels.get(i).getLogId().equals(logModel.getLogId())){
                logModels.set(i, logModel);
                break;
            }
        }
        logModels.removeIf(log -> log.getLogId().equals(logModel.getLogId()));

        // 3.写进文件
        this.adaptee.writeLogFile(logModels);
    }

    @Override
    public void removeLog(LogModel logModel) {
        // 1.读取日志对象
        List<LogModel> logModels = this.adaptee.readLogFile();

        // 2.删除日志对象
        logModels.removeIf(log -> log.getLogId().equals(logModel.getLogId()));

        // 3.写进文件
        this.adaptee.writeLogFile(logModels);
    }

    @Override
    public List<LogModel> getAllLog() {
        return this.adaptee.readLogFile();
    }
}
